package com.ebupt.migu.music.common.util.FileUtil;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import com.ebupt.migu.music.common.entity.ResultObject;
import com.ebupt.migu.music.common.exception.StatusEnum;
import com.ebupt.migu.music.common.util.pojo.UploadResponse;

import lombok.extern.slf4j.Slf4j;

/**
 * @author xuhongsong
 * @version 1.0
 * @date 2020/8/31 10:11
 */
@RestController
@RequestMapping("/upload")
@Slf4j
public class FileUploadsController {

    @Value("${upload.service-type}")
    private String SERVICE_TYPE;

    @Value("${upload.upload-url}")
    private String UPLOAD_URL;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 上传发送者头像
     *
     * @return
     */
    @RequestMapping(value = "/imageFile")
    public ResultObject imageFile(@RequestParam("file") MultipartFile file) throws Exception {
        ResultObject res = new ResultObject();
        // 图片名称
        String fileName = file.getOriginalFilename();
        log.info("文件名：" + fileName);
        String names = fileName.substring(fileName.lastIndexOf(".") + 1);
        String newFileName = System.currentTimeMillis() + "." + names;
        Map<String, Object> retMap = new HashMap<String, Object>();
        String resultUrl = upload(file);
        log.info("返回的图片路径：{}", resultUrl);
        if (null == resultUrl) {
            res.setCode(StatusEnum.UPLOAD.getCode());
            res.setMsg(StatusEnum.UPLOAD.getMsg());
        } else {
            res.setCode(StatusEnum.SUCCESS.getCode());
            res.setMsg(StatusEnum.SUCCESS.getMsg());
        }
        retMap.put("iconReName", newFileName);
        retMap.put("icon", resultUrl);
        retMap.put("filePath", resultUrl);
        retMap.put("oriName", fileName);
        retMap.put("reName", newFileName);
        res.setData(retMap);
        return res;
    }

    /**
     * 请求方法
     * 
     * @param files
     * @return
     */
    public String upload(MultipartFile files) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<String, Object>();
        try {
            ByteArrayResource resource = new ByteArrayResource(files.getBytes()) {
                @Override
                public String getFilename() {
                    return files.getOriginalFilename();
                }
            };
            params.add("files", resource);
            params.add("serviceType", SERVICE_TYPE);
            HttpEntity<MultiValueMap<String, Object>> requestEntity =
                new HttpEntity<MultiValueMap<String, Object>>(params, headers);
            ResponseEntity<UploadResponse> response =
                restTemplate.exchange(UPLOAD_URL, HttpMethod.POST, requestEntity, UploadResponse.class);
            log.info("请求地址:{},type:{}", UPLOAD_URL, SERVICE_TYPE);
            log.info("body:{}", response.getBody());
            return Optional.ofNullable(response).map(e -> e.getBody()).map(e -> e.getData()).map(e -> e.get(0))
                .map(e -> e.getUrl()).orElse(null);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
